import {uSelectUserDevExceptionLog} from '@/api/exceptionManagement'
import {CCard} from '@/components/card'
import {IconImg} from '@/components/image'
import {DeviceSelect} from '@/components/select/device'
import {SplitLine} from '@/components/splitLine'
import {CnBoldP, CnBoldSpan, CnMediumSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {getUserId} from '@/libs/auth'
import {time2str} from '@/libs/date'
import dayjs, {Dayjs} from 'dayjs'
import {selectExceptionTypeApi} from '@/api/selectlogType.ts'
import './index.less'
import {toStandardConfig} from '@/libs/pageRedirect'

type TableColumn = CColumn<Exception.TableData>

export default defineComponent({
  name: 'dataOverview',
  setup() {
    const {store} = useGlobalAPI()
    const state = reactive<{
      devList: Exception.DeviceListData[]
      tableDatas: Exception.TableData[]
      tableTotal: number
      currentDevId: number | undefined
      tableLoading: boolean
      dateRange: [string, string]
      pagation: Paging
    }>({
      currentDevId: undefined,

      dateRange: ['', ''],
      devList: [],
      tableDatas: [],
      tableTotal: 0,
      pagation: {
        page: 1,
        size: 20
      },
      tableLoading: false
    })

    const columns: TableColumn[] = [
      {
        title: '设备名称',
        dataIndex: 'devName'
      },
      {
        title: '异常类型',
        dataIndex: 'devEventTypeName',
        width: 160,
        align: 'center'
      },
      {
        title: '异常内容',
        dataIndex: 'devLogContent'
      },
      {
        title: '异常时间',
        dataIndex: 'createTime',
        width: 220,
        align: 'center'
        // customRender({text}) {
        //   let value = time2str(text)
        //   return value
        // }
      }
      // {
      //   title: '是否已读',
      //   dataIndex: 'isRead',
      //   width: 120,
      //   align: 'center',

      //   customRender({text, column}) {
      //     if (column.dataIndex === 'isRead') {
      //       return text === '1' ? '已读' : '未读'
      //     } else {
      //       return text
      //     }
      //   }
      // }
    ]

    const disposeDataRangeDataFunc = (data: any) => {
      let obj = {
        startTime: '',
        endTime: ''
      }
      if (data[0] == '') {
      } else {
        obj.startTime = data[0].format('YYYY-MM-DD 00:00:00')
      }

      if (data[1] == '') {
      } else {
        obj.endTime = data[1].format('YYYY-MM-DD 23:59:59')
      }
      return obj
    }

    function getTableData() {
      const userId = getUserId()
      if (!userId) return
      state.tableLoading = true
      const timeData = disposeDataRangeDataFunc(state.dateRange)
      const startTime = timeData.startTime
      const endTime = timeData.endTime
      const page = state.pagation.page
      const size = state.pagation.size
      uSelectUserDevExceptionLog({
        userId,
        devId: state.currentDevId,
        startTime,
        endTime,
        page: page,
        size: size,
        exceptionCode: currentSelectedTypeCode.value
      })
        .then(res => {
          state.tableDatas = res.data.list
          // console.log(state.tableDatas);

          state.tableTotal = res.data.total
          nextTick(() => {
            store.dispatch('layoutMain/MAINSCROLLTOTOP')
          })
          state.tableLoading = false
        })
        .catch(err => {
          state.tableLoading = false
        })
    }

    function resetSearchLine() {
      state.currentDevId = undefined
      state.dateRange = ['', '']
    }

    watch(
      () => state.currentDevId,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.dateRange,
      n => {
        getTableData()
      },
      {deep: true}
    )

    watch(
      () => state.pagation,
      n => {
        getTableData()
      },
      {deep: true}
    )

    // 异常类型列表数据
    const exceptionTypeList = ref([])

    // 当前选择的类型code
    const currentSelectedTypeCode = ref('')

    const tagCheckChange = (currentCode: any, e: any) => {
      console.log(currentCode)
      currentSelectedTypeCode.value = currentCode
      getTableData()
    }

    // 查询异常类型列表的函数
    const selectExceptionTypeFunc = async () => {
      const res = await selectExceptionTypeApi()
      // console.log(res, 'selectExceptionTypeFunc-res')
      exceptionTypeList.value = res.data
      console.log(exceptionTypeList.value, 'exceptionTypeList.value')
    }

    onMounted(() => {
      getTableData()
      selectExceptionTypeFunc()
    })

    return () => (
      <div class=''>
        <CnBoldP class='mt-11 text-20'>异常管理</CnBoldP>
        <CnNormalP class='mt-6 text-4xText'>根据您设置的水质标准，为您监测水质</CnNormalP>
        <CCard class=' mt-20 bg-white' title='报警信息' canHoverMove={false}>
          <div class='w-full mt-16 type_box'>
            <CnBoldSpan class='mr-16'>异常类型：</CnBoldSpan>
            <div class='tag_checked_box'>
              <a-checkable-tag
                checked={currentSelectedTypeCode.value == ''}
                onChange={(e: any) => {
                  tagCheckChange('', e)
                }}
              >
                <CnNormalSpan>所有类型</CnNormalSpan>
              </a-checkable-tag>
              {exceptionTypeList.value.map((ettl, i) => (
                <a-checkable-tag
                  class={`${
                    currentSelectedTypeCode.value == ettl.exceptionCode
                      ? 'tags tag_' + ettl.exceptionCode
                      : ''
                  }`}
                  checked={currentSelectedTypeCode.value == ettl.exceptionCode}
                  onChange={(e: any) => {
                    tagCheckChange(ettl.exceptionCode, e)
                  }}
                >
                  <CnNormalSpan>{ettl.exceptionName}</CnNormalSpan>
                </a-checkable-tag>
              ))}
            </div>
          </div>
          <div class='mt-19 h-32 flex items-center'>
            <CnBoldSpan class='mr-16'>选择设备：</CnBoldSpan>
            <DeviceSelect v-model={[state.currentDevId, 'value']}></DeviceSelect>
            <SplitLine class='mx-16'></SplitLine>
            <CnBoldSpan class='mr-16'>时间范围：</CnBoldSpan>
            <a-range-picker
              v-model={[state.dateRange, 'value']}
              allowClear={false}
            ></a-range-picker>
            <SplitLine class='mx-16'></SplitLine>
            <a-button class='bg-primary mr-16'>
              <div class='flex items-center'>
                <IconImg class='w-16 h-16 mr-8' imgName='magnifying-glass'></IconImg>
                <CnNormalSpan class='text-white' onClick={getTableData}>
                  查询
                </CnNormalSpan>
              </div>
            </a-button>
            <a-button class='bg-info mr-16'>
              <div class='flex items-center'>
                <CnNormalSpan class='text-white' onClick={() => resetSearchLine()}>
                  重置
                </CnNormalSpan>
              </div>
            </a-button>
            <a-button class='bg-redirectBtn'>
              <CnNormalSpan onClick={toStandardConfig}>标准设置</CnNormalSpan>
            </a-button>
          </div>

          <a-table
            class='mt-20'
            id='alarmTable'
            loading={state.tableLoading}
            columns={columns}
            dataSource={state.tableDatas}
            pagination={{
              current: state.pagation.page,
              pageSize: state.pagation.size,
              size: 'small',
              total: state.tableTotal,
              showTotal: (total: number) => `共 ${total} 条`,
              onChange: (page: number, size: number) => {
                state.pagation = {
                  page,
                  size
                }
              }
            }}
          ></a-table>
        </CCard>
      </div>
    )
  }
})
